package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkCloseConsumerReqData(data common.CloseConsumerReqData) error {
	// Check if transport ID is provided
	if data.TransportId == "" {
		return errors.New("transport ID is required in close consumer request")
	}

	// Check if consumer ID is provided
	if data.ConsumerId == "" {
		return errors.New("consumer ID is required in close consumer request")
	}

	// Check if router ID is provided
	if data.RouterId == "" {
		return errors.New("router ID is required in close consumer request")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) sendCloseConsumerResponse(rid string, code int, msg string,
	data common.CloseConsumerReqData) {
	resMsg := common.Message{
		Cmd: common.CLOSE_CONSUMER_RES,
		Rid: rid,
		Data: common.ResMsgData{
			Code: code,
			Msg:  msg,
			Data: common.CloseConsumerResData{
				TransportId: data.TransportId,
				ConsumerId:  data.ConsumerId,
				RouterId:    data.RouterId,
			},
		},
	}

	if err := s.wsClient.Send(resMsg); err != nil {
		LOG(rid).WithError(err).Error("failed to send close consumer response")
	}
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleCloseConsumerReq(msg common.Message) {
	LOG(msg.Rid).WithField("msg", common.ToJson(msg)).Info("handling close consumer request")

	var reqData common.CloseConsumerReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to decode close consumer request data")
		s.sendCloseConsumerResponse(msg.Rid, 1, err.Error(), reqData)
		return
	}

	if err := s.checkCloseConsumerReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid close consumer request data")
		s.sendCloseConsumerResponse(msg.Rid, 1, err.Error(), reqData)
		return
	}

	if err := s.CloseConsumer(msg.Rid, reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to close consumer")
		s.sendCloseConsumerResponse(msg.Rid, 1, err.Error(), reqData)
		return
	}

	s.sendCloseConsumerResponse(msg.Rid, 0, "Consumer closed successfully", reqData)
}
